<?php

namespace app\admin\logic;

use app\common\exception\LogicException;
use app\common\logic\EncryptLogic;
use app\common\logic\RandCreateStrLogic;
use app\model\Admin;
use think\facade\Db;

class AdminLogic
{
    protected Admin $model;
    protected int $admin_id;

    public function __construct()
    {
        $this->model = new Admin();
        $this->admin_id = request()->admin_info['admin_id'];
    }

    /**
     * @Description 列表
     * @author: zj
     * @param array $param
     * @time 2024/07/09 16:56:39
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param)
    {
        $query = $this->model
            ->field('id,name,phone,create_time,update_time')
            ->where('delete_time',$this->model::IS_DELETE_NO);
        if ($param['name']) {
            $query->where('name','like','%'.trim($param['name']).'%');
        }
        if ($param['phone']) {
            $query->where('phone','like','%'.trim($param['phone']).'%');
        }
        if ($param['create_time_start']) {
            $query->where('create_time','>=',strtotime($param['create_time_start']));
        }
        if ($param['create_time_end']) {
            $query->where('create_time','<=',strtotime($param['create_time_end']));
        }

        return $query->order('id DESC')
            ->paginate([
                'page' => $param['page'],
                'list_rows' => $param['page_size']
            ])
            ->toArray();
    }

    /**
     * @Description 新增
     * @author: zj
     * @param string $name
     * @param string $phone
     * @time 2024/07/09 18:18:54
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(string $name,string $phone)
    {
        if ($this->model->checkNameIsExist($name)) {
            throw new LogicException(4000,'用户名已存在');
        }
        if ($this->model->checkPhoneIsExist($phone)) {
            throw new LogicException(4000,'手机号码已注册');
        }

        $randStrLogic = new RandCreateStrLogic();
        $salt = $randStrLogic->create(4);

        $logic = new EncryptLogic();

        Db::startTrans();
        try {
            $adminId = $this->model->insertGetId([
                'name' => $name,
                'phone' => $phone,
                'salt' => $salt,
                'password' => $logic->encryptMD5('123456',$salt),
                'create_time' => request()->time(),
                'update_time' => request()->time()
            ]);

            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();
            throw new LogicException($e->getCode(),$e->getMessage());
        }

        return true;
    }

    /**
     * @Description 编辑
     * @author: zj
     * @param int $id
     * @param array $param
     * @time 2024/07/09 18:24:44
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(int $id,array $param)
    {
        $exist = $this->model->checkIsExist($id);
        if (!$exist) {
            throw new LogicException(4000,'用户不存在');
        }
        $updateData = [];
        if ($param['name']) {
            $userName = $this->model->checkNameIsExist($param['name']);
            if ($userName && $userName != $exist) {
                throw new LogicException(4000,'用户名已存在');
            }
            $updateData['name'] = $param['name'];
        }
        if ($param['phone']) {
            $userPhone = $this->model->checkPhoneIsExist($param['phone']);
            if ($userPhone && $userPhone != $exist) {
                throw new LogicException(4000,'手机号码已注册');
            }
            $updateData['phone'] = $param['phone'];
        }
        $updateData['update_time'] = request()->time();

        $this->model->where('id',$id)->update($updateData);

        return true;
    }

    /**
     * @Description 删除
     * @author: zj
     * @param int $id
     * @time 2024/07/09 18:29:52
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del(int $id)
    {
        if (!$this->model->checkIsExist($id)) {
            throw new LogicException(4000,'数据不存在');
        }
        if ($id == $this->admin_id) {
            throw new LogicException(4000,'不能删除自己');
        }
        if (in_array($id,$this->model::SUPPER_ADMIN)) {
            throw new LogicException(4000,'该用户不可删除');
        }

        $this->model->where('id',$id)
            ->update([
                'delete_time' => request()->time()
            ]);

        return true;
    }

    /**
     * @Description 详情
     * @author: zj
     * @param int $id
     * @time 2024/07/10 10:29:41
     * @return mixed
     */
    public function detail(int $id)
    {
        $info = $this->model
            ->field('id,name,phone,create_time,update_time')
            ->where('id',$id)
            ->where('delete_time',$this->model::IS_DELETE_NO)
            ->find();
        if (!$info) {
            throw new LogicException(4000,'数据不存在');
        }

        return $info->toArray();
    }

    /**
     * @Description 选择列表
     * @author: zj
     * @param array $param
     * @time 2024/07/10 10:29:53
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function selectList(array $param)
    {
        $query = $this->model
            ->field('id,name,phone')
            ->where('delete_time',$this->model::IS_DELETE_NO);
        if ($param['name']) {
            $query->where('name','like','%'.trim($param['name']).'%');
        }
        if ($param['phone']) {
            $query->where('phone','like','%'.trim($param['phone']).'%');
        }

        return $query->order('id DESC')
            ->paginate([
                'page' => $param['page'],
                'list_rows' => $param['page_size']
            ])
            ->toArray();
    }

    /**
     * @Description 修改密码
     * @author: zj
     * @param string $oldPassword
     * @param string $newPassword
     * @time 2024/07/10 10:50:07
     * @return true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function modifyPassword(string $oldPassword,string $newPassword)
    {
        $adminInfo = $this->model->field('password,salt')
            ->where('id', $this->admin_id)
            ->where('delete_time', $this->model::IS_DELETE_NO)
            ->find();
        if (!$adminInfo) {
            throw new LogicException(4000,'获取用户信息失败');
        }

        $encrypt = new EncryptLogic();
        if (!$encrypt->checkMD5Str($oldPassword, $adminInfo['salt'],$adminInfo['password'])) {
            throw new LogicException(4000,'旧密码错误');
        }

        $randLogic = new RandCreateStrLogic();
        $salt = $randLogic->create(4);
        $encryptPassword = $encrypt->encryptMD5($newPassword, $salt);

        $this->model->where('id', $this->admin_id)
            ->update([
                'password' => $encryptPassword,
                'salt' => $salt,
                'update_time' => request()->time()
            ]);

        return true;
    }

}